//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.skipper.spring.cloud.aspect;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Order(-2147483648)
@Aspect
@Component
public class RequestLogAspect {

    private static final Logger logger = LogManager.getLogger(RequestLogAspect.class);
    private static final boolean LOGGER_REQUEST_ENABLED = true;

    public RequestLogAspect() {
    }

    public static boolean isLoggerRequestEnabled() {
        return LOGGER_REQUEST_ENABLED;
    }

    @Pointcut("execution(public * com.yixiang.*.controller..*.*(..))")
    public void cutController() {
    }

    @Pointcut(" cutController()")
    private void doAspect() {
    }

    @Around("doAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        if (LOGGER_REQUEST_ENABLED) {
            long start = System.currentTimeMillis();
            String requestUrl = null;

            try {
                requestUrl = this.getRequestUri();
            } catch (Exception var11) {
                logger.error("getRequestUri error.", var11);
            }

            String clazzName = joinPoint.getTarget().getClass().getCanonicalName();
            String methodName = joinPoint.getSignature().getName();
            Object[] args = joinPoint.getArgs();

            try {
                result = joinPoint.proceed();
            } catch (Exception var10) {
                this.saveRequestLog(requestUrl, clazzName, methodName, args, result, System.currentTimeMillis() - start, var10);
                throw var10;
            }

            this.saveRequestLog(requestUrl, clazzName, methodName, args, result, System.currentTimeMillis() - start, (Exception) null);
        } else {
            result = joinPoint.proceed();
        }

        return result;
    }

    private String getRequestUri() {
        String requestUrl = null;
        if (null != RequestContextHolder.getRequestAttributes()) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            requestUrl = request.getRequestURL().toString();
        }

        return requestUrl;
    }

    private void saveRequestLog(String requestUrl, String moduleName, String methodName, Object[] args, Object result, long time, Exception e) {
        String inputStr = null;
        String outputStr = null;

        try {
            if (args != null) {
                args = this.filterHttpServletRequest(args);
                inputStr = JSON.toJSONString(args);
            }

            if (result != null) {
                if (result instanceof File) {
                    File file = (File) result;
                    outputStr = String.format("返回是个文件，不记录,FileName:%s  FileSize:%s", file.getName(), file.length());
                } else if (result instanceof String) {
                    outputStr = (String) result;
                } else if (result instanceof ResponseEntity) {
                    ResponseEntity entity = (ResponseEntity) result;
                    outputStr = this.objectToJsonString(entity.getBody());
                } else {
                    outputStr = this.objectToJsonString(result);
                }
            }
        } catch (Exception var12) {
            logger.error("saveRequestLog exception.", var12);
            outputStr = "保存请求记录异常";
        }

        boolean recordException = null != e && (StringUtils.isEmpty(moduleName) || moduleName.contains("Controller"));
        if (recordException) {
            logger.error(" RequestUrl : {}, MethodName : {}.{}(), processTime : {}ms, Input : {}, Output : {}. {}", new Object[]{requestUrl, moduleName, methodName, time, inputStr, outputStr, "Exception : ", e});
        } else {
            logger.info(" RequestUrl : {}, MethodName : {}.{}(), processTime : {}ms, Input : {}, Output : {}.", new Object[]{requestUrl, moduleName, methodName, time, inputStr, outputStr});
        }

    }

    private Object[] filterHttpServletRequest(Object[] args) {
        List<Object> objects = new ArrayList<>();
        if (args != null) {
            for (Object obj : args) {
                if (!(obj instanceof HttpServletRequest) && !(obj instanceof HttpServletResponse) && !(obj instanceof File) && !(obj instanceof MultipartFile) && !(obj instanceof byte[])) {
                    objects.add(obj);
                }
            }
        }

        return objects.toArray();
    }

    private String objectToJsonString(Object obj) {
        String str = "";

        try {
            if (obj instanceof String) {
                str = (String) obj;
            } else {
                str = JSON.toJSONString(obj);
            }
        } catch (Exception var4) {
            logger.info("objectToJsonString failed, className:{}", obj == null ? "" : obj.getClass().getCanonicalName());
        }

        return str;
    }
}
